package com.liuxu.topnews.acitivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.liuxu.topnews.AccessService;
import com.liuxu.topnews.MyApplication;
import com.liuxu.topnews.R;
import com.liuxu.topnews.Adapter.RecycleAdapter;
import com.liuxu.topnews.utils.PathUtils;
import com.liuxu.topnews.utils.SettingUtils;
import com.liuxu.topnews.bean.App;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.liuxu.topnews.MyApplication.toast;

public class RecycleFragment extends Fragment {
//
    public boolean check=true;
    public static String version;
    private int index;
    private int currentTabIndex=0;
    private Fragment[] mFragments;
    public static List<CheckBox> checkBoxList;
    public Button button1;
    public Button button2;
    public Button button3;
    public Button button4;
    public View view;
    public MainActivity parentActivity;
    public Intent intent;
    public SettingUtils settingUtils;
    public ArrayList<App> defaultapps=new ArrayList<>();
    RecyclerView recyclerView;
    RecycleAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.setting_fragment, container, false);
        parentActivity= (MainActivity ) getActivity();
        initView();
        initListener();

        return view;
    }
    private void initView(){
        button1 = (Button)view.findViewById(R.id.button1);
        button2 = (Button)view. findViewById(R.id.button2);
        button3 = (Button)view. findViewById(R.id.button3);
        button4 = (Button)view. findViewById(R.id.button4);
        recyclerView= (RecyclerView)view.findViewById(R.id.recycler_view);
        settingUtils=new  SettingUtils();
        defaultapps=settingUtils.GetDefaultXml();
        adapter=new RecycleAdapter(parentActivity.getApplicationContext(),defaultapps);
        LinearLayoutManager layoutManager=new LinearLayoutManager(parentActivity.getApplicationContext());
        layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        mFragments=new Fragment[]{new RecycleFragment(),new InfoFragment()};
        intent = new Intent(parentActivity.getApplicationContext(), AccessService.class);
    }
    private void initListener() {

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<App> apps = adapter.apps;
                saveSetting(apps,true);
//                adapter.update(apps);
                showtoast("保存成功",true);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent,1);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<App> apps = adapter.apps;
                saveSetting(apps,false);
                showtoast("文件已导出到根目录下：read_setting.xml",true);
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultapps=settingUtils.GetXml(true);
                adapter.update(defaultapps);
                showtoast("已恢复默认配置",true);
            }
        });

    }
    public ArrayList<App> getApps(){
        ArrayList<App> apps = new ArrayList<App>();
        RecyclerView recy =view.findViewById(R.id.recycler_view);
        for (int i = 0; i < recy.getChildCount(); i++) {
            App app=new App();
            LinearLayout layout = (LinearLayout) recy.getChildAt(i);
            TextView textView1=layout.findViewById(R.id.appid);
            TextView textView2=layout.findViewById(R.id.appname);
            EditText editText1=layout.findViewById(R.id.word1);
            EditText editText2=layout.findViewById(R.id.word2);
            EditText editText3=layout.findViewById(R.id.word3);
            app.setId(textView1.getText().toString());
            app.setZname(textView2.getText().toString());
            app.setUptime(Integer.parseInt(editText1.getText().toString()));
            app.setDowntime(Integer.parseInt(editText2.getText().toString()));
            app.setPagenumber(Integer.parseInt(editText3.getText().toString()));
            apps.add(app);
        }
        return apps;
    }
    public void saveSetting(ArrayList<App> apps,boolean selfspace){
        StringBuffer sb = new StringBuffer();
        //封装一个声明头
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        //封装根节点
        sb.append("<apps>");
        //循环遍历list集合封装所有的短信
        for (App app : apps) {
            sb.append("<app>");
            sb.append("<id>");
            sb.append(app.getId());
            sb.append("</id>");
            sb.append("<zname>");
            sb.append(app.getZname());
            sb.append("</zname>");
            sb.append("<uptime>");
            sb.append(app.getUptime());
            sb.append("</uptime>");
            sb.append("<downtime>");
            sb.append(app.getDowntime());
            sb.append("</downtime>");
            sb.append("<pagenumber>");
            sb.append(app.getPagenumber());
            sb.append("</pagenumber>");
            sb.append("</app>");
        }
        sb.append("</apps>");
        FileOutputStream openFileOutput  = null;
        try{
            //将stringBuffer中的xml字符串写入私有目录中的文件
            if (selfspace){
                openFileOutput = MyApplication.getContext().openFileOutput("read_setting.xml", MyApplication.getContext().MODE_PRIVATE);
            }else {
                openFileOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getCanonicalPath() + "/read_setting.xml");
            }
            openFileOutput.write(sb.toString().getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(openFileOutput != null){
                try{
                    openFileOutput.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            String path= new PathUtils().GetPath(uri);
            ArrayList<App> apps = settingUtils.GetXml(path);
            adapter.update(apps);
            showtoast("导入成功",true);
        }
    }
    public void showtoast(final String text, final boolean now){
        Handler handlerThree=new Handler(
                Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                if (now) {
                    toast.setText(text);
                    toast.show();
                } else {
                    Toast.makeText(MyApplication.getContext(),text,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
